package com.huluobo.a2203kotlinjetpackdemo.lifeCycle

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.huluobo.a2203kotlinjetpackdemo.R

class ADActivity : AppCompatActivity() {
    private var timing = 10000L

    private lateinit var adViewModel: ADViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_adactivity2)

        val time = findViewById<TextView>(R.id.time)
        val cancel = findViewById<Button>(R.id.btn_cancel)
        adViewModel = ViewModelProvider(this)[ADViewModel::class.java]

//        val adManager = ADManager(adViewModel.timing)//相当于在sp中取值
        val adManager = ADManager(adViewModel)

        //观察者是AdManager,被观察者是当前的activity
        //通过lifecycle产生订阅关系
        //观察者模式的三要素已经齐全
        lifecycle.addObserver(adManager)

//        adManager.adManagerListener = object : ADManager.ADManagerListener {
//            override fun timing(second: Int) {
//                time.text = "广告剩余时间:${second}秒"
//                adViewModel.timing = second.toLong() * 1000//相当于在sp中存值
//            }
//
//            override fun finish() {
//                val intent = Intent(this@ADActivity, MainActivity::class.java)
//                this@ADActivity.startActivity(intent)
//                this@ADActivity.finish()
//            }
//        }

        //观察LiveData的完整写法,一般接口会省略掉
//        adViewModel.timingResult.observe(this, object : Observer<Long> {
//            override fun onChanged(t: Long?) {
//
//            }
//        })

        adViewModel.timingResult.observe(this) {
            time.text = "广告剩余时间:${it}秒"
            if (it <= 1L) {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }

        cancel.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }
}